<?php
/**
 * Created by PhpStorm.
 * User: Daniel
 * Date: 2017/12/16
 * Time: 22:27
 */

namespace app\controllers;

use app\components\LoginStateComponent;
use app\models\LoginForm;
use app\models\User;
use Yii;
use yii\data\ArrayDataProvider;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use yii\web\Session;
use \yii\web\Request;

class TableController extends Controller
{
    /**
     * @var Request $request
     */
    public $request = '';

    /**
     * @var Session  $session
     */
    public $session;
    /**
     * @var string $sessionId
     */
    public $sessionId;

    /**
     * @var LoginStateComponent $loginState
     */
    public $loginState;

    public function init()
    {
        parent::init();
        $this->request = Yii::$app->request;
        $this->session = Yii::$app->session;
        $this->sessionId = $this->session->getId();
        $this->loginState = Yii::$app->loginState;
    }

    /**
     * @param \yii\base\Action $action
     * @return bool
     */
    public function beforeAction($action)
    {
        if (!$this->session->getIsActive()) {
            Yii::warning('session open:');
            $this->session->open();
        }
        Yii::warning('session id:' . $this->sessionId);
        return parent::beforeAction($action);
    }
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        $params = [
            'userId' => $this->loginState->getState('userId'),
            'sessionId' => $this->loginState->getState('sessionId'),
            'pageIndex' => '1',
            'pageSize' => '10'
        ];
        $deviceList = Yii::$app->util->postJson('/getDeviceList', $params);
        $list = $deviceList['data']['devices'];
        return $this->render('index', [
            'list' => $list
        ]);
    }
    public function actionInfo()
    {
        $deviceId = $this->request->get('deviceId');
        $params = [
            'userId' => $this->loginState->getState('userId'),
            'sessionId' => $this->loginState->getState('sessionId'),
            'deviceId' => $deviceId,
            'operations' => '$PHKJ#GET#STATUS#0#12*'
        ];
        $deviceInfo = Yii::$app->util->postJson('/operateDevice', $params);
    }

    /**
     * Login action.
     *
     * @return Response|string
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        }
        return $this->render('login', [
            'model' => $model,
        ]);
    }

    /**
     * Displays the registration page.
     * After successful registration if enableConfirmation is enabled shows info message otherwise
     * redirects to home page.
     *
     * @return string
     * @throws \yii\web\HttpException
     */
    public function actionRegister()
    {
        if (!$this->module->enableRegistration) {
            throw new NotFoundHttpException();
        }
        /** @var RegistrationForm $model */
        $model = \Yii::createObject(RegistrationForm::className());
        $event = $this->getFormEvent($model);
        $this->trigger(self::EVENT_BEFORE_REGISTER, $event);
        $this->performAjaxValidation($model);
        if ($model->load(\Yii::$app->request->post()) && $model->register()) {
            $this->trigger(self::EVENT_AFTER_REGISTER, $event);
            return $this->render('/message', [
                'title'  => \Yii::t('user', 'Your account has been created'),
                'module' => $this->module,
            ]);
        }
        return $this->render('register', [
            'model'  => $model,
            'module' => $this->module,
        ]);
    }

    /**
     * Logout action.
     *
     * @return Response
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }



    /***********************************************************************************************/
    //daniel 开始位置
    /**************************************************************************************************/


    public function actionTable(){

        $startDate = isset($_REQUEST['start']) ? $_REQUEST['start'] : date("Y-m-d");
        $endDate = isset($_REQUEST['end']) ? $_REQUEST['end'] : date("Y-m-d");
        $deviceId = isset($_REQUEST['deviceId']) ? $_REQUEST['deviceId'] : "20171200001";
        $switchNum = isset($_REQUEST['switchNum']) ? $_REQUEST['switchNum'] : "1";

        $params = [
            'userId' => $this->loginState->getState('userId'),
            'sessionId' => $this->loginState->getState('sessionId'),
            'deviceId'  => $deviceId,
            "switchNum" => $switchNum,
            "startDate" => $startDate." 00:00:00",
            "endDate"   => $endDate." 23:59:59",
            'pageIndex' => '1',
            'pageSize'  => '1000000'
        ];

        $dataList = Yii::$app->util->postJson('/getADStatusList', $params);
        $list = $dataList['data']['statusList'];

        $mode = array("定时模式","流量模式","手动模式");


        if(empty($list)){
            $list = array();
        }else{
            foreach($list as &$l){
                $l['mode'] = $mode[substr( $l['aDStatus'], 0, 1 )];
                $l['rate'] = substr( $l['aDStatus'], 5, 2 );
                $l['frate'] = substr( $l['aDStatus'], 11, 2 );
                $l['up'] = substr( $l['aDStatus'], 7, 2 );
                $l['low'] = substr( $l['aDStatus'], 9, 2 );
            }
        }




//echo json_encode($list);exit;
//        //var_dump($dataList);exit;
//
//
//
//
//        $i = rand(100,1000);
//
//        for($i;$i<1000;$i++){
//            $list[] = array(
//                    "updateTime" => date("Y-m-d H:i:s"),
//                    "mode" => "自动",
//                    "rate" => rand(40,75),
//                    "up"   => 75,
//                    "low"  => 25,
//                    "time" => 1.28 + $i,
//                    "times" => $i
//            );
//        }


        $switch  = array(1=>"1路",2=>"2路",3=>"3路");

        $select = "";
        foreach($switch as $key => $v){

            if($switchNum == $key){
                $select .= '<option value="'.$key.'" selected="selected">'.$v.'</option>';
            }else{
                $select .= '<option value="'.$key.'">'.$v.'</option>';
            }

        }
        return $this->render('table',["list" => $list,"start"=>$startDate,"end" => $endDate,"deviceId"=>$deviceId,"switchNum"=>$select]);
    }


    public function actionCharts(){




        return $this->render('chart');
    }

    public function actionUsers(){
        $params = [
            'userId' => $this->loginState->getState('userId'),
            'sessionId' => $this->loginState->getState('sessionId'),
            'pageIndex' => '1',
            'pageSize'  => '10000'
        ];
        $dataList = Yii::$app->util->postJson('/getUserList', $params);
        $list = $dataList['data']['userInfoModels'];

        if(empty($list)){
            $list = array();
        }
        return $this->render('users',["list" => $list]);
    }

    public $enableCsrfValidation = false;
    public function actionSave(){
        $uid = $_REQUEST['uid'];
        $role = $_REQUEST['role'];
        $userName = $_REQUEST['userName'];


        $params = [
            'userId' => $this->loginState->getState('userId'),
            'sessionId' => $this->loginState->getState('sessionId'),
            'simpleUserName' => $userName,
            'role'  => $role
        ];
        $res = Yii::$app->util->postJson('/manageUserAuth', $params);

        $this->redirect(array('table/users'));
    }


    public function actionData(){
        $startDate = isset($_REQUEST['start']) ? $_REQUEST['start'] : date("Y-m-d");
        $deviceId = isset($_REQUEST['deviceId']) ? $_REQUEST['deviceId'] : "20171200001";
        $params = [
            'userId' => $this->loginState->getState('userId'),
            'sessionId' => $this->loginState->getState('sessionId'),
            'deviceId'  => $deviceId,
            "switchNum" => "1",
            "startDate" => $startDate." 00:00:00",
            "endDate"   => $startDate." 23:59:59",
            'pageIndex' => '1',
            'pageSize'  => '1000000'
        ];


        $dataList = Yii::$app->util->postJson('/getADStatusList', $params);
        $list = $dataList['data']['statusList'];

        $a = array();
        if(!empty($list)){
            foreach($list as $l){
                $a[] =array(strtotime($l['uploadTime'])*1000,(substr( $l['aDStatus'], 5, 2 ))/100);
            }
        }

        echo json_encode($a) ;
        exit;
    }

    public function actionAjax(){
        $startDate = isset($_REQUEST['start']) ? $_REQUEST['start'] : date("Y-m-d");
        $endDate = isset($_REQUEST['end']) ? $_REQUEST['end'] : date("Y-m-d");
        $deviceId = isset($_REQUEST['deviceId']) ? $_REQUEST['deviceId'] : "20171200005";

        $params = [
            'userId' => $this->loginState->getState('userId'),
            'sessionId' => $this->loginState->getState('sessionId'),
            'deviceId'  => $deviceId,
            "switchNum" => "1",
            "startDate" => $startDate." 00:00:00",
            "endDate"   => $endDate." 23:59:59",
            'pageIndex' => '1',
            'pageSize'  => '1000000'
        ];

        $dataList = Yii::$app->util->postJson('/getADStatusList', $params);
        $list = $dataList['data']['statusList'];

        foreach($list as $l){
            $a[] =array(strtotime($l['uploadTime'])*1000,(substr( $l['aDStatus'], 5, 2 ))/100);
        }

        echo json_encode($a) ;
        exit;
    }


    public function actionPoint(){

        $startDate = isset($_REQUEST['start']) ? $_REQUEST['start'] : date("Y-m-d H:i:s",(time()-300));
        $endDate = isset($_REQUEST['end']) ? $_REQUEST['end'] : date("Y-m-d H:i:s");
        $deviceId = isset($_REQUEST['deviceId']) ? $_REQUEST['deviceId'] : "20171200005";

        $params = [
            'userId' => $this->loginState->getState('userId'),
            'sessionId' => $this->loginState->getState('sessionId'),
            'deviceId'  => $deviceId,
            "switchNum" => "1",
            "startDate" => $startDate,
            "endDate"   => $endDate,
            'pageIndex' => '1',
            'pageSize'  => '1000000'
        ];

        $dataList = Yii::$app->util->postJson('/getADStatusList', $params);
        $list = $dataList['data']['statusList'];

        $a = array();
        if(!empty($list)){
            foreach($list as $l){
                $a[] =array(strtotime($l['uploadTime'])*1000,(substr( $l['aDStatus'], 5, 2 ))/100);
            }
        }

        echo json_encode($a) ;
        exit;
    }

}
